package com.wejoy.video.middle.station.data.util;

import org.bouncycastle.util.encoders.Hex;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * Aes 加密/解密工具类
 */
public class AesUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";


    public String encrypt(String input, String key) {
        byte[] decodeKey = Hex.decode(key);
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(decodeKey, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return parseByte2HexStr(crypted);

    }

    /**
     * 解密
     *
     * @param content  原文
     * @param key      安全key
     * @param platform 平台 @see EnumPlatform
     * @return
     * @throws Exception
     */
    public static String decrypt(String content, String key, Integer platform) throws Exception {
        content = new String(new BASE64Decoder().decodeBuffer(content));
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        byte[] keyBytes = key.getBytes();
        SecretKeySpec sk = new SecretKeySpec(keyBytes, "AES");
        //7.初始化密码器，第一个参数为加密(Encrypt_mode)或者解密(Decrypt_mode)操作，第二个参数为使用的KEY
        cipher.init(Cipher.DECRYPT_MODE, sk);
        byte[] bytes = parseHexStr2Byte(content);
        byte[] decode = cipher.doFinal(bytes);
        return new String(decode, "utf-8");
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;

    }

    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();

    }
}
